package com.restaurant.application.signin;

import com.nebutown.base.ViewSpec;
import com.nebutown.base.data.View;
import com.nebutown.commonunits.utils.DateTimeUtils;
import com.nebutown.generation.basictype.UID;
import com.restaurant.application.accumulate.Accumulate;
import com.restaurant.application.accumulate.support.AccumulateData;
import com.restaurant.application.configsignin.ConfigSignIn;
import com.restaurant.application.customer.Customer;
import com.restaurant.application.indexes.signinlist.mysql.SignInListBean;
import com.restaurant.application.indexes.signinlist.mysql.SignInListCriteria;
import com.restaurant.application.indexes.signinlist.mysql.SignInListImpl;
import com.restaurant.application.minifacade.data.SignInBO;
import com.restaurant.application.signin.support.AbstractSignIn;
import com.restaurant.application.util.GetDateUtil;

import java.time.LocalDate;
import java.util.List;

public class SignInImpl extends AbstractSignIn {
    @Override
    public View getFullView() {
        return null;
    }

    @Override
    public View getViewLead(ViewSpec viewSpec) {
        return null;
    }

    @Override
    public SignInBO init() {
        SignInBO resultBean = new SignInBO();
        UID uid = getGate();
        Long startOfDay = GetDateUtil.getStartOfDay(LocalDate.now());
        List<SignInListBean> search = getIndex(SignInListImpl.class)
                .search(new SignInListCriteria().withCustomerUidEquals(uid).withSignTimeLower(startOfDay), null, 1);
        if (search.size() > 0) {
            resultBean.setMessage("今天已经签到");
            return resultBean;
        }
        getData().setSignInTime(DateTimeUtils.getCurrentMillisecond());
        getData().setCustomer(uid);
        resultBean.setMessage("success");
        Integer signInScore = getSingleton(ConfigSignIn.class).getSignInScore();
        getUnit(Customer.class, uid).plusScores(signInScore);
        resultBean.setIntegral(signInScore);
        // 创建积分
        Accumulate accumulate = (Accumulate) createNode(Accumulate.class.getName());
        AccumulateData accumulateData = new AccumulateData().withType(Accumulate.ACCUMULATE_INCREASE_SIGNIN)
                .withAccumulate((long) signInScore).withAction(DateTimeUtils.getCurrentDateTimeStr()
                        + Accumulate.ACCUMULATE_INCREASE_SIGNIN + signInScore + "积分").withCustomerUID(uid)
                .withDetail(getId());
        accumulate.init(accumulateData);
        insertBean();
        return resultBean;
    }

    private void insertBean() {
        SignInListBean bean = new SignInListBean().withCustomerUid(getGate()).withSignInUid(getId())
                .withSignTime(DateTimeUtils.getCurrentMillisecond());
        getIndex(SignInListImpl.class).insert(bean);
    }
}
